package com.bxd.baodan.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.item.GanHuoBean;
import com.bxd.baodan.item.JoinSearchBean;
import com.bxd.baodan.item.ProductItem;
import com.bxd.baodan.item.QuestionItem;
import com.bxd.baodan.item.ThinkWordBean;
import com.bxd.baodan.util.GlideUtil;
import com.bxd.baodan.util.GsonUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.KeyWordUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.SortUtil;
import com.bxd.baodan.util.SpKey;
import com.bxd.baodan.util.SpUtil;
import com.bxd.baodan.util.StringUtil;
import com.bxd.baodan.widget.SearchView;
import com.umeng.analytics.MobclickAgent;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2018/1/11.
 */

public class SearchAllActivity extends BaseActivity {
    private LinearLayout historyLy;
    private TagFlowLayout historyTagLayout;
    private LinearLayout searchThinkLy;
    private ListView searchThinkLv;
    private ImageView historyDelIv;
    private TextView searchThinkTv;
    private LinearLayout searchJoinLy;
    private LinearLayout searchProductLy;
    private ListView searchProductLv;
    private TextView searchProductMoreTv;
    private LinearLayout searchQuestionLy;
    private ListView searchQuestionLv;
    private TextView searchQuestionMoreTv;
    private LinearLayout searchArticleLy;
    private ListView searchArticleLv;
    private TextView searchArticleMoreTv;

    private SearchView searchView;
    private String key;
    private TextView no_answer;


    private CommonAdapter<ThinkWordBean.ThinkWordItem> thinkWordIAdapter;
    List<ThinkWordBean.ThinkWordItem> thinkList = new ArrayList<>();
    private CommonAdapter<GanHuoBean> artileAdapter;
    private List<GanHuoBean> articleList = new ArrayList<>();

    private CommonAdapter<ProductItem> productAdapter;
    private List<ProductItem> productList = new ArrayList<>();

    private CommonAdapter<QuestionItem> questionAdapter;
    private List<QuestionItem> questionList = new ArrayList<>();
    private TextView article_count, product_count, question_count;

    private List<String> historyList = new ArrayList<>();
    TagAdapter<String> historyAdapter;

    public final static String HISTORY = "history";
    public final static String THINK = "think";
    public final static String JOIN = "join";

    private String hintStr = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_all);
        setSearchBar();
        initView();
        setAdapter();

        getHotWord();


        getHistoryData();


        searchView.setSearchViewListener(new SearchView.SearchViewListener() {
            @Override
            public void textChanged(String text) {

                if (!hintStr.isEmpty()) {
                    hintStr = "";
                    searchView.et.setHint("请输入关键词");

                }

                key = text;
                getThinkWordData();
                showViewVisible(THINK);
            }

            @Override
            public void onSearch(String text, int cate_id) {
                if (text.isEmpty() && !hintStr.isEmpty()) {
                    text = hintStr;
                }
                if (text.isEmpty()) {
                    return;
                }

                historyList.add(text);

                SortUtil.removeDuplicateWithOrder(historyList);
                String historyData = GsonUtil.toJson(historyList);
                SpUtil.getInstance().savaString(SpKey.SEARCH_HISTORY, historyData);
                key = text;
                getJoinData();


            }

            @Override
            public void onEmpty() {

                key = "";
                getHistoryData();

            }
        });


    }

    private void getHistoryData() {
        showViewVisible(HISTORY);
        String history = SpUtil.getInstance().getString(SpKey.SEARCH_HISTORY);
        historyList.clear();
        if (StringUtil.isEmpty(history)) {
            historyLy.setVisibility(View.GONE);
            historyAdapter.notifyDataChanged();
            return;
        }
        List<String> his = GsonUtil.fromJsonList(history, String.class);
        historyList.addAll(his);
        historyLy.setVisibility(View.VISIBLE);
        historyAdapter.notifyDataChanged();

    }

    private void getJoinData() {
        NetUtil netUtil = new NetUtil(SearchAllActivity.this, JsonApi.COMMON_SEARCH);
        LogUtil.e("joinKey: " + key);
        netUtil.setParams("keyword", key);
        netUtil.postRequest("加载", new NetUtil.DataListener() {
            @Override
            public void onComplete(String data) {
                // TODO: 18/1/13 接口要改数据

                JoinSearchBean joinData = new Gson().fromJson(data, JoinSearchBean.class);
                JoinSearchBean.ArticleSearchBean article = joinData.article;
                JoinSearchBean.ProductSearchBean product = joinData.product;
                JoinSearchBean.QuestionSearchBean question = joinData.question;


                articleList.clear();
                productList.clear();
                questionList.clear();


                if (articleList != null) {

                    article_count.setText(article.count + "");
                    articleList.addAll(article.list);

                }


                if (productList != null) {
                    product_count.setText(product.count + "");
                    productList.addAll(product.list);
                }

                if (questionList != null) {
                    question_count.setText(question.count + "");
                    questionList.addAll(question.list);

                }
                questionAdapter.notifyDataSetChanged();
                productAdapter.notifyDataSetChanged();
                artileAdapter.notifyDataSetChanged();
                showJoinViewVisible();


            }
        });

    }

    private void showJoinViewVisible() {
        showViewVisible(JOIN);

        searchArticleLy.setVisibility(articleList.isEmpty() ? View.GONE : View.VISIBLE);
        searchProductLy.setVisibility(productList.isEmpty() ? View.GONE : View.VISIBLE);
        searchQuestionLy.setVisibility(questionList.isEmpty() ? View.GONE : View.VISIBLE);

        if (articleList.isEmpty() && productList.isEmpty() && questionList.isEmpty()) {
            no_answer.setVisibility(View.VISIBLE);
        } else {
            no_answer.setVisibility(View.GONE);
        }
    }

    private void showViewVisible(String str) {
        historyLy.setVisibility(View.GONE);
        searchThinkLy.setVisibility(View.GONE);
        searchJoinLy.setVisibility(View.GONE);

        switch (str) {
            case JOIN:
                searchJoinLy.setVisibility(View.VISIBLE);
                break;
            case THINK:
                searchThinkLy.setVisibility(View.VISIBLE);
                searchThinkTv.setText("查看【" + key + "】的搜索结果");
                searchThinkTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setKeyAndSearch(key);
                    }
                });
                break;
            case HISTORY:
                historyLy.setVisibility(View.VISIBLE);
                break;
        }

    }

    private void getThinkWordData() {
        NetUtil netUtil = new NetUtil(SearchAllActivity.this, JsonApi.COMMON_KEYWORDSEARCH);
        LogUtil.e("thinkey: " + key);
        netUtil.setParams("keyword", key);
        netUtil.postRequest("", new NetUtil.DataListener() {
            @Override
            public void onComplete(String data) {
                ThinkWordBean bean = (ThinkWordBean) GsonUtil.fromJson(data, ThinkWordBean.class);

                List<ThinkWordBean.ThinkWordItem> list = bean.list;
                thinkList.clear();
                if (list != null) {
                    if (list.size() > 5) {
                        for (int i = 0; i < 5; i++) {
                            thinkList.add(list.get(i));
                        }
                    } else {
                        thinkList.addAll(list);
                    }

                }

                thinkWordIAdapter.notifyDataSetChanged();
            }
        });

    }

    private void setAdapter() {

        thinkWordIAdapter = new CommonAdapter<ThinkWordBean.ThinkWordItem>(this, thinkList, R.layout.layout_think_word) {
            @Override
            public void convert(ViewHolder holder, final ThinkWordBean.ThinkWordItem item) {
                if (holder.getPosition() < 5) {
                    holder.getView(R.id.main).setVisibility(View.VISIBLE);
                    TextView tv = holder.getView(R.id.tv);
                    SpannableString spannableString = KeyWordUtil.matcherSearchTitle(Color.parseColor("#999999"), item.qk_name, key);
                    tv.setText(spannableString);
                    tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            setKeyAndSearch(item.qk_name);


                            thinkList.clear();
                            thinkWordIAdapter.notifyDataSetChanged();
                            searchThinkLy.setVisibility(View.GONE);
                        }
                    });
                } else {
                    holder.getView(R.id.main).setVisibility(View.GONE);
                }
            }
        };

        historyAdapter = new TagAdapter<String>(historyList) {
            @Override
            public View getView(FlowLayout parent, int position, final String str) {
                final TextView tv = (TextView) getLayoutInflater().inflate(R.layout.tv_1, historyTagLayout, false);
                tv.setText(str);
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setKeyAndSearch(str);
                        historyLy.setVisibility(View.GONE);
                        searchJoinLy.setVisibility(View.VISIBLE);
                        searchThinkLy.setVisibility(View.GONE);
                    }
                });
                return tv;
            }
        };

        artileAdapter = new CommonAdapter<GanHuoBean>(this, articleList, R.layout.gan_huo_item) {
            @Override
            public void convert(ViewHolder holder, final GanHuoBean item) {
                GlideUtil.loadImage(SearchAllActivity.this, item.image, ((ImageView) holder.getView(R.id.image)));
                TextView tv = holder.getView(R.id.title);
                SpannableString spannableString = KeyWordUtil.matcherSearchTitle(Color.parseColor("#16c571"), item.title, key);
                tv.setText(spannableString);
                holder.setText(R.id.read, item.viewCount + "阅读");
                holder.getView(R.id.main).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{item.url});
                    }
                });


            }
        };

        productAdapter = new CommonAdapter<ProductItem>(this, productList, R.layout.product_item_new) {
            @Override
            public void convert(ViewHolder holder, final ProductItem item) {
                TextView name = holder.getView(R.id.p_name);
                SpannableString nameSpan = KeyWordUtil.matcherSearchTitle(Color.parseColor("#16c571"), item.p_name, key);
                name.setText(nameSpan);

                TextView p_features = holder.getView(R.id.p_features);
                SpannableString featuresSpan = KeyWordUtil.matcherSearchTitle(Color.parseColor("#16c571"), item.p_features, key);
                p_features.setText(featuresSpan);


                if (StringUtil.isEmpty(item.cat_name)) {
                    holder.getView(R.id.cat_name).setVisibility(View.GONE);
                } else {
                    holder.setText(R.id.cat_name, item.cat_name);
                }

                if (StringUtil.isEmpty(item.price)) {
                    holder.getView(R.id.p_price).setVisibility(View.GONE);
                    holder.getView(R.id.explain).setVisibility(View.GONE);

                } else {
                    holder.setText(R.id.p_price, item.price);
                    holder.getView(R.id.p_price).setVisibility(View.VISIBLE);
                    holder.getView(R.id.explain).setVisibility(View.VISIBLE);
                }

                GlideUtil.loadImage(SearchAllActivity.this, item.p_img, (ImageView) holder.getView(R.id.p_image));


                holder.getView(R.id.p_view).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //item.p_url= "https://ztg.zhongan.com/promote/entrance/promoteEntrance.do?redirectType=h5&promotionCode=INST171047535012&productCode=PRD160436305017&promoteCategory=single_product&token=";

                        openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{item.p_url});
                    }
                });


            }
        };

        questionAdapter = new CommonAdapter<QuestionItem>(this, questionList, R.layout.question_detail_item) {
            @Override
            public void convert(ViewHolder holder, final QuestionItem item) {

                // 问题
                TextView questioner = (TextView) holder.getView(R.id.asker);
                ImageView quesAvatar = (ImageView) holder.getView(R.id.asker_img);
                TextView quesTime = (TextView) holder.getView(R.id.ask_time);
                TextView quesContent = (TextView) holder.getView(R.id.question_content);
                TextView replayCount = (TextView) holder.getView(R.id.answer_count);


                RelativeLayout answerLayout = (RelativeLayout) holder.getView(R.id.answer_layout);
                ImageView answerAvatar = (ImageView) holder.getView(R.id.answer_avatar);
                TextView answer = (TextView) holder.getView(R.id.answer_name);
                TextView answerContent = (TextView) holder.getView(R.id.answer_content);
                ImageView verify_icon = (ImageView) holder.getView(R.id.verify_icon);
                ImageView official_iv = (ImageView) holder.getView(R.id.official_iv);
                ImageView robot_sign = (ImageView) holder.getView(R.id.robot_sign);
                ImageView is_bestAnswer = (ImageView) holder.getView(R.id.iv_is_bestAnswer);

                GlideUtil.loadCircle(SearchAllActivity.this, item.getU_avatar(), quesAvatar);
                questioner.setText(item.getU_nick());
                quesTime.setText(item.getQ_create_date());

                SpannableString span = KeyWordUtil.matcherSearchTitle(Color.parseColor("#16c571"), item.getQ_title(), key);
                quesContent.setText(span);
                replayCount.setText(item.getQ_answer_count() + "");

                holder.getView(R.id.main).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String uid = "";
                        if (LoginInfo.getInstance().isLogin()) {
                            uid = LoginInfo.getInstance().getUser().getU_id();
                        }
                        openActivity(QuestionDetailActivity.class, new String[]{"qid", "q_title"}, new String[]{item.getQ_id() + "", item.getQ_title()});
                    }
                });

                if (item.getQa_answer_info() != null && item.getQa_answer_info().getQa_id() != null) {

                    answerLayout.setVisibility(View.VISIBLE);
                    if (item.getQa_answer_info().getIsBestAnswer() == 1) {
                        answerLayout.setBackground(getResources().getDrawable(R.drawable.shape_yellow_a7_r));
                        is_bestAnswer.setVisibility(View.VISIBLE);

                    } else {
                        answerLayout.setBackground(getResources().getDrawable(R.drawable.shape_gray_a7_r));
                        is_bestAnswer.setVisibility(View.GONE);
                    }


                    GlideUtil.loadCircle(SearchAllActivity.this, item.getQa_answer_info().getAvatar(), answerAvatar);
                    answer.setText(item.getQa_answer_info().getName());
                    SpannableString span1 = KeyWordUtil.matcherSearchTitle(Color.parseColor("#16c571"), item.getQa_answer_info().getQa_title(), key);
                    answerContent.setText(span1);

                    // TODO: 2017/3/27 身份认证要改
                    if (item.getQa_answer_info().agent_mark != null && item.getQa_answer_info().agent_mark.length > 0
                            && Arrays.asList(item.getQa_answer_info().agent_mark).contains("6")) {
                        verify_icon.setVisibility(View.VISIBLE);
                    } else {
                        verify_icon.setVisibility(View.GONE);
                    }
                    if (item.getQa_answer_info().agent_mark != null && item.getQa_answer_info().agent_mark.length > 0
                            && Arrays.asList(item.getQa_answer_info().agent_mark).contains("8")) {
                        official_iv.setVisibility(View.VISIBLE);
                    } else {
                        official_iv.setVisibility(View.GONE);
                    }

                    if (item.getQa_answer_info().src != null && item.getQa_answer_info().src.equals("6")) {
                        robot_sign.setVisibility(View.VISIBLE);
                    } else {
                        robot_sign.setVisibility(View.GONE);
                    }

                } else {
                    answerLayout.setVisibility(View.GONE);
                }
            }

        };


        historyTagLayout.setAdapter(historyAdapter);
        searchThinkLv.setAdapter(thinkWordIAdapter);
        searchArticleLv.setAdapter(artileAdapter);
        searchProductLv.setAdapter(productAdapter);
        searchQuestionLv.setAdapter(questionAdapter);


    }

    private void setKeyAndSearch(String str) {
        key = str;
        searchView.et.setText(str);
        searchView.search(key);

    }

    private void initView() {
        searchView = findViewById(R.id.search_view);
        searchView.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        historyLy = (LinearLayout) findViewById(R.id.history_ly);
        historyDelIv = (ImageView) findViewById(R.id.history_del_iv);
        historyTagLayout = (TagFlowLayout) findViewById(R.id.id_flowlayout);
        searchThinkLy = (LinearLayout) findViewById(R.id.search_think_ly);
        searchThinkLv = (ListView) findViewById(R.id.search_think_lv);
        searchThinkTv = (TextView) findViewById(R.id.search_think_tv);
        searchJoinLy = (LinearLayout) findViewById(R.id.search_join_ly);
        searchProductLy = (LinearLayout) findViewById(R.id.search_product_ly);
        searchProductLv = (ListView) findViewById(R.id.search_product_lv);
        searchProductMoreTv = (TextView) findViewById(R.id.search_product_more_tv);
        searchQuestionLy = (LinearLayout) findViewById(R.id.search_question_ly);
        searchQuestionLv = (ListView) findViewById(R.id.search_question_lv);
        searchQuestionMoreTv = (TextView) findViewById(R.id.search_question_more_tv);
        searchArticleLy = (LinearLayout) findViewById(R.id.search_article_ly);
        searchArticleLv = (ListView) findViewById(R.id.search_article_lv);
        searchArticleMoreTv = (TextView) findViewById(R.id.search_article_more_tv);
        article_count = findViewById(R.id.article_count);
        product_count = findViewById(R.id.product_count);
        question_count = findViewById(R.id.question_count);
        no_answer = findViewById(R.id.no_answer);
        searchView.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchAllActivity.this.finish();
            }
        });

        historyDelIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SpUtil.getInstance().savaString(SpKey.SEARCH_HISTORY, "");
                getHistoryData();
            }
        });

        searchProductMoreTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isEmpty(key)) {
                    key = hintStr;
                }
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_ss_cpMore");
                openActivity(SearchProduceActivity.class, new String[]{"key"}, new String[]{key});
            }
        });

        searchArticleMoreTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isEmpty(key)) {
                    key = hintStr;
                }
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_ss_wzMore");
                openActivity(SearchArticleActivity.class, new String[]{"key"}, new String[]{key});
            }
        });

        searchQuestionMoreTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isEmpty(key)) {
                    key = hintStr;
                }
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_ss_wdMore");
                openActivity(SearchQuestionActivity.class, new String[]{"key"}, new String[]{key});
            }
        });
    }


    public void getHotWord() {
        NetUtil netUtil = new NetUtil(this, JsonApi.THINK_WORD);
        netUtil.setParams("inputPos", "index");
        netUtil.postRequest("", new NetUtil.DataListener() {
            @Override
            public void onComplete(String data) {
                String key = JSONUtil.getData("keyword", data);
                searchView.et.setHint(key);
                hintStr = key;

            }
        });
    }
}
